from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
import pandas as pd
import numpy as np
data=pd.read_csv("E:/GraduateDesign/LinearUse.csv")
X = data.drop(columns=['rrr'])
y = data['rrr']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, shuffle=True)


model = GradientBoostingRegressor()


model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(f"RMSE: {mean_squared_error(y_test, y_pred, squared=False)}")
print(f"MAE: {mean_absolute_error(y_test, y_pred)}")
# 新增MAPE指标（处理除零问题）
# 方法1: 自动过滤零值样本
mask = y_test != 0
mape = np.mean(np.abs((y_test[mask] - y_pred[mask]) / y_test[mask])) * 100

# 方法2: 添加微小值防止除零（如果数据允许）
# epsilon = 1e-10
# mape = np.mean(np.abs((y_test - y_pred) / (y_test + epsilon))) * 100

print(f"MAPE: {mape:.2f}%")


# 新增R²指标
r2 = r2_score(y_test, y_pred)
print(f"R²: {r2}")
